<?php

namespace app\controllers\merchant\storehouse;

use app\models\merchant\storehouse\StorehouseModel;
use app\models\shop\GoodsModel;
use app\models\shop\StockModel;
use app\models\tuan\LeaderModel;
use app\models\tuan\WarehouseModel;
use yii;
use yii\web\MerchantController;

/**
 * 仓库
 * @author  wmy
 * Class StorehouseController
 * @package app\controllers\merchant\storehouse
 */
class StorehouseController extends MerchantController
{

    public $enableCsrfValidation = false; //禁用CSRF令牌验证，可以在基类中设置

    public function behaviors() {
        return [
            'token' => [
                'class' => 'yii\filters\MerchantFilter', //调用过滤器
                'except' => ['check-goods-code'], //指定控制器不应用到哪些动作
            ]
        ];
    }
    /**
     * 查询列表
     * @return array
     * @throws yii\db\Exception
     */
    public function actionList()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $must = ['key'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            if (isset($params['searchName'])) {
                if ($params['searchName'] != "") {
                    $params['name'] = ['like', "{$params['searchName']}"];
                }
                unset($params['searchName']);
            }
            $model = new StorehouseModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            $array = $model->do_select($params);
            if ($array['status'] == 200) {
                foreach ($array['data'] as &$storehouse_val) {
                    $storehouse_id = $storehouse_val['id'];
                    $sql = "SELECT SUM(storehouse_number) as total FROM shop_stock
                            WHERE  `status` = 1 and `storehouse_id` = {$storehouse_id}";
                    $total = yii::$app->db->createCommand($sql)->queryOne();
                    $storehouse_val['goods_number'] = $total['total'] ? $total['total'] : 0;
                }
            }
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 查询单条
     * @return array
     */
    public function actionOne()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            if (!$params['id']) {
                return result(500, "缺少id");
            }
            $must = ['key'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $model = new StorehouseModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            $array = $model->do_one($params);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 新增
     * @return array
     */
    public function actionAdd()
    {
        if (yii::$app->request->isPost) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $model = new StorehouseModel();
            //设置类目 参数
            $must = ['name', 'address', 'location', 'key'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $params['merchant_id'] = yii::$app->session['uid'];
            $array = $model->do_add($params);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 更新
     * @param $id
     * @return array
     */
    public function actionUpdate($id)
    {
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $model = new StorehouseModel();
            if (!$id) {
                return result(400, "缺少参数 id");
            }
            $must = ['key'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $where['key'] = $params['key'];
            $where['id'] = $id;
            unset($params['key']);
            $where['merchant_id'] = yii::$app->session['uid'];
            $array = $model->do_update($where, $params);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     * @throws yii\db\Exception
     */
    public function actionDelete($id)
    {
        if (yii::$app->request->isDelete) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $model = new StorehouseModel();
            $params['id'] = $id;
            $must = ['key'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $params['merchant_id'] = yii::$app->session['uid'];
            if (!isset($params['id'])) {
                return result(500, "缺少参数 id");
            } else {
                //检测是否有商品 有则不能删除
                $goodsModel = new GoodsModel();
                $goodsInfo = $goodsModel->one(['storehouse_id' => $id]);
                if ($goodsInfo['status'] == 200) {
                    return result(500, "此仓库下有商品不能删除");
                }
                $transaction = Yii::$app->db->beginTransaction();
                $array = $model->do_delete($params);
                if ($array['status'] == 200) {
                    //将该仓库下的团长解绑
                    $leaderModel = new LeaderModel();
                    $info = $leaderModel->do_one(['storehouse_id' => $id, 'key' => $params['key']]);
                    if($info['status'] == 200){
                        $res = $leaderModel->do_update(['storehouse_id' => $id, 'key' => $params['key']], ['storehouse_id' => 0]);
                        if ($res['status'] == 200) {
                            $transaction->commit();
                            return $res;
                        }
                        $transaction->rollBack();
                        return $res;
                    }else{
                        $transaction->commit();
                        return $array;
                    }
                }
                $transaction->rollBack();
                return result(500, "删除失败");
            }

        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 查询团长
     * @return array
     * @throws yii\db\Exception
     */
    public function actionSearchLeader()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $must = ['key'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $leaderModel = new LeaderModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            $params['storehouse_id'] = 0;
            $array = $leaderModel->do_select($params);
            if($array['status'] == 200){
                foreach ($array['data'] as $key=>&$val){
                    $warehouseModel = new WarehouseModel();
                    $val['route'] =  '';
                    if(isset($val['uid']) && !empty($val['uid'])){
                        $warehouseList = $warehouseModel->do_select(['leader_uid' => $val['uid'],'key' => $params['key'],'field' => 'name']);
                        if($warehouseList['status'] == 200){
                            $val['route'] =  implode(',',array_column($warehouseList['data'],'name'));
                        }
                    }
                }
            }
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 绑定团长
     * @return array
     * @throws yii\db\Exception
     */
    public function actionBindLeader()
    {
        if (yii::$app->request->isPost) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $must = ['key', 'leader_ids', 'storehouse_id'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $leaderModel = new LeaderModel();
            $model = new StorehouseModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            $leader_ids = $params['leader_ids'];
            $params['leader_ids'] = explode(',', $params['leader_ids']);
            if (empty($params['leader_ids'])) {
                return result(500, "团长id数据出错");
            }
            $storehouseInfo = $model->do_one(['id' => $params['storehouse_id']]);
            if ($storehouseInfo['status'] != 200) {
                return result(500, "仓库信息错误");
            }
            $tmp1 = [];
            $transaction = Yii::$app->db->beginTransaction();
            if ($storehouseInfo['data']['leader_ids']) {
                $storehouseInfo['data']['leader_ids'] = explode(',', $storehouseInfo['data']['leader_ids']);
                foreach ($storehouseInfo['data']['leader_ids'] as $ids) {
                    $tmp1[] = (int)$ids;
                }
                $array = $leaderModel->do_update(['in', 'id', $tmp1], ['storehouse_id' => 0]);
                if ($array['status'] != 200) {
                    $transaction->rollBack();
                    return result(500, "请求失败");
                }
            }
            $tmp = [];
            foreach ($params['leader_ids'] as $val_id) {
                $tmp[] = (int)$val_id;
            }
            $params['leader_ids'] = $tmp;
            $array = $leaderModel->do_update(['in', 'id', $params['leader_ids']], ['storehouse_id' => $params['storehouse_id']]);
            if ($array['status'] != 200) {
                $transaction->rollBack();
                return result(500, "请求失败");
            }
            $array = $model->do_update(['id' => $params['storehouse_id']], ['leader_ids' => $leader_ids]);
            if ($array['status'] != 200) {
                $transaction->rollBack();
                return result(500, "请求失败");
            }
            $transaction->commit();
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 解绑团长
     * @return array
     * @throws yii\db\Exception
     */
    public function actionDeleteLeader()
    {
        if (yii::$app->request->isDelete) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参
            $must = ['key', 'leader_id', 'storehouse_id'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $leaderModel = new LeaderModel();
            $model = new StorehouseModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            $storehouseInfo = $model->do_one(['id' => $params['storehouse_id']]);
            if ($storehouseInfo['status'] != 200) {
                return result(500, "仓库信息错误");
            }
            $transaction = Yii::$app->db->beginTransaction();
            $array = $leaderModel->do_update(['id'=>$params['leader_id'],'storehouse_id' => $params['storehouse_id']], ['storehouse_id' => 0]);
            if ($array['status'] != 200) {
                $transaction->rollBack();
                return result(500, "请求失败");
            }
            $leader_ids = explode(',',$storehouseInfo['data']['leader_ids']);
            $leader_ids = implode(',',array_merge(array_diff($leader_ids, array($params['leader_id']))));
            $array = $model->do_update(['id' => $params['storehouse_id']], ['leader_ids' => $leader_ids]);
            if ($array['status'] != 200) {
                $transaction->rollBack();
                return result(500, "请求失败");
            }
            $transaction->commit();
           return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 仓库详情
     * @param $id
     * @return array
     * @throws yii\db\Exception
     */
    public function actionStorehouseDetail($id)
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $must = ['key'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $model = new StorehouseModel();
            $params['merchant_id'] = yii::$app->session['uid'];
            $params['id'] = $id;
            $storehouseInfo = $model->do_one($params);
            if ($storehouseInfo['status'] != 200) {
                return result(500, "仓库信息错误");
            }
            $leaderModel = new LeaderModel();
            $array = $leaderModel->do_select(['storehouse_id' => $id, 'key' => $params['key']]);
            if ($array['status'] == 200) {
                foreach ($array['data'] as &$val) {
                    $val['warehouse_name'] = '';
                    if ($val['warehouse_id']) {
                        $warehouseModel = new WarehouseModel();
                        $warehouseInfo = $warehouseModel->do_one(['id' => $val['warehouse_id']]);
                        if ($warehouseInfo['status'] == 200) {
                            $val['warehouse_name'] = $warehouseInfo['data']['name'];
                        }
                    }
                    $warehouseModel = new WarehouseModel();
                    $val['route'] =  '';
                    if(isset($val['uid']) && !empty($val['uid'])){
                        $warehouseList = $warehouseModel->do_select(['leader_uid' => $val['uid'],'key' => $params['key'],'field' => 'name']);
                        if($warehouseList['status'] == 200){
                            $val['route'] =  implode(',',array_column($warehouseList['data'],'name'));
                        }
                    }
                }
            }
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 查询商品
     * @return array
     */
    public function actionSearchGoods()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $must = ['key', 'storehouse_id'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            if (empty($params['storehouse_id'])) {
                return result(500, "仓库id不能为空");
            }
            if (isset($params['goods_id']) && !empty($params['goods_id'])) {
                $searchWhere['goods_id'] = $params['goods_id'];
            }
            if (isset($params['goods_name']) && !empty($params['goods_name'])) {
                $searchWhere["name like '%{$params['goods_name']}%'"] = null;
            }
            if (isset($params['code']) && !empty($params['code'])) {
                $searchWhere['code'] = $params['code'];
            }
            $searchWhere['`key`'] = $params['key'];
            $searchWhere['storehouse_id'] = $params['storehouse_id'];
            $searchWhere['merchant_id'] = yii::$app->session['uid'];
            $goodsModel = new StockModel();
            $array = $goodsModel->findGoods($searchWhere);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    /**
     * 校验商品规格编码唯一性
     * @return array
     * @throws yii\db\Exception
     */
    public function actionCheckGoodsCode(){
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $must = ['code'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            if(!is_numeric($params['code'])){
                return result(500, "商品码只能是数字组合");
            }
            if(strlen($params['code']) < 6 || strlen($params['code']) > 17){
                return result(500, "商品码长度在6-16位之间");
            }
            $searchWhere['code'] = $params['code'];
            $goodsModel = new StockModel();
            $array = $goodsModel->find($searchWhere);
            if($array['status'] == 200){
                return result(500, "商品码已被使用");
            }
            return result(200, "请求成功");
        } else {
            return result(500, "请求方式错误");
        }
    }
}
